package com.zdsoft.crm.controller.auth;

import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zdsoft.crm.controller.BaseController;
import com.zdsoft.crm.entity.auth.SysUser;
import com.zdsoft.crm.service.auth.ISysUserService;


@Controller
@RequestMapping("/auth/user")
public class UserController extends BaseController {

	@Autowired
	ISysUserService sysUserService;

	@GetMapping("/list")
	public ModelAndView list(@RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
			@RequestParam(name = "username", defaultValue = "") String username) {
		ModelAndView mav=new ModelAndView("auth/user/list.html", "list", sysUserService.findPage(pageNum, pageSize,username));
		mav.addObject("", "");//模糊查询
		return mav; // 
	}

	@GetMapping("/")
	public ModelAndView saveUI() {
	
		ModelAndView mav=new ModelAndView("auth/user/form.html");
		
		return mav;
	}

	@PostMapping("/")
	public String save(SysUser user) {
		//验证
		
		
		user.setId(UUID.randomUUID().toString().replace("-", ""));
		user.setPassword(new StandardPasswordEncoder().encode(user.getPassword()));
		
		
		sysUserService.saveUser(user);
		return "redirect:/auth/user/list";
	}

	@GetMapping("/{id}")
	public ModelAndView updateUI(@PathVariable("id") String id) {
		
		ModelAndView mav=new ModelAndView("auth/user/form.html");
		
		SysUser user=sysUserService.findById(id);
		
		mav.addObject("user", user);
		
		return mav;
	}

	/**
	 * 编辑提交
	 * @return
	 */
	@PostMapping("/{id}")
	public String update(@PathVariable("id") String id,String username,Integer is_admin) {
		
		sysUserService.update(id, username, is_admin);
		
		return "redirect:/auth/user/list";
	}

	/**
	 * 删除
	 * @param id
	 */
	@DeleteMapping("/{id}")
	@ResponseBody
	public void delete(@PathVariable("id") String id) {
		
		sysUserService.deleteUser(id);
	}
	
}
